package com.brokendust.client.api;

import com.brokendust.client.listener.PlayerListener;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraftforge.fml.network.NetworkRegistry;
import net.minecraftforge.fml.network.simple.SimpleChannel;

import java.nio.charset.StandardCharsets;
import java.util.function.Supplier;

public class PixelConnect {
    private static int IDX = 100;
    public SimpleChannel channel;

    TextFieldWidget textFieldWidget;

    public PixelConnect() {
        FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff);
    }

    private void doClientStuff(FMLClientSetupEvent event) {
        (this.channel = NetworkRegistry.ChannelBuilder
                .named(new ResourceLocation("pixelengine", "pixelgui"))
                .networkProtocolVersion(() -> "http.protocol.version")
                .clientAcceptedVersions(s -> true)
                .serverAcceptedVersions(s -> true)
                .simpleChannel()
        )
                .registerMessage(159, String.class, this::enc, this::dec, this::proc);
    }

    private void enc(String str, PacketBuffer buffer) {
        buffer.writeBytes(str.getBytes(StandardCharsets.UTF_8));
    }

    private String dec(PacketBuffer buffer) {
        return buffer.toString(StandardCharsets.UTF_8);
    }

    private void proc(String str, Supplier<NetworkEvent.Context> supplier) {
        PlayerListener.onReceiveServerMessage(str);
        NetworkEvent.Context context = supplier.get();
        context.setPacketHandled(true);
    }

    public void send(String type, String message) {
        try {
            this.channel.sendToServer(type + " : " + message);
        } catch (NullPointerException ex) {
        }
    }
}
